﻿using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Desktop.AddIns;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ArcMapUI;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using System.Data;
using ESRI.ArcGIS.ArcMapUI;
using System.Windows.Forms;
using System.Globalization;

namespace AgrinsaAddIn
{
    public class EditLote : ESRI.ArcGIS.Desktop.AddIns.Tool
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public EditLote()
        {
            _nombreCapa = "Lote";
            ArcMap.Document.FocusMap.ClearSelection();
            ArcMap.Document.ActiveView.Refresh();
        }


        #region PROPIEDADES Y VARIABLES

        private IActiveView m_focusMap;
        private ESRI.ArcGIS.Display.INewEnvelopeFeedback m_lineFeedback;
        private bool m_isMouseDown/* = false*/;
        private IPoint _point;
        private IFeatureLayer featureLayer;
        private IFeatureClass featureClass;
        private static string _nombreCapa = string.Empty;

        public static string NombreCapa
        {
            get { return _nombreCapa; }
            set { _nombreCapa = value; }
        }

        private static IFeatureClass _featClass;
        public static IFeatureClass FeatClass
        {
            get { return EditLote._featClass; }
            set { EditLote._featClass = value; }
        }

        private static string _objectId = string.Empty;
        public static string ObjectId
        {
            get { return EditLote._objectId; }
            set { EditLote._objectId = value; }
        }

        private static bool _activar;
        public static bool Activar
        {
            get { return EditLote._activar; }
            set { EditLote._activar = value; }
        }

        WPF.WPFLotes formulario;
        #endregion

        #region eventosMouse

        protected override void OnMouseDown(MouseEventArgs arg)
        {
            IMxDocument mxDoc = ArcMap.Document;
            m_focusMap = mxDoc.FocusMap as IActiveView;
            _point = m_focusMap.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;

            m_isMouseDown = true;
        }
        protected override void OnMouseMove(MouseEventArgs arg)
        {
            try
            {
                if (!m_isMouseDown)
                    return;

                IMxDocument mxDoc = ArcMap.Document;
                IActiveView activeView = mxDoc.FocusMap as IActiveView;
                if (m_lineFeedback == null)
                {
                    m_lineFeedback = new ESRI.ArcGIS.Display.NewEnvelopeFeedbackClass();
                    m_lineFeedback.Display = m_focusMap.ScreenDisplay;
                    m_lineFeedback.Start(_point);
                }
                _point = m_focusMap.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;
                m_lineFeedback.MoveTo(_point);
            }
            catch (Exception ex)
            {

            }

        }
        protected override void OnUpdate()
        {
            this.Enabled = true;
        }
        protected override void OnMouseUp(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs args)
        {

            try
            {
                GetFeatures();

                m_isMouseDown = false;
                ArcMap.Application.CurrentTool = null;

            }
            catch (Exception ex)
            {

            }

        }

        #endregion

        /// <summary>
        /// Obtiene los features seleccionados
        /// </summary>
        private void GetFeatures()
        {
            List<string> list = new List<string>();
            list.Add("SHAPE");
            list.Add("GLOBALID");
            DataTable dt = new DataTable();
            IMxDocument doc = ArcMap.Document;
            IFeature feature = null; ;
            IEnumFeature enumFeature = null; ;
            IEnvelope env = null; ;
            string capa = NombreCapa;
            
            for (int i = 0; i < ArcMap.Document.FocusMap.LayerCount; i++)
            {
                featureLayer = ArcMap.Document.FocusMap.get_Layer(i) as IFeatureLayer;
                if (featureLayer == null)
                    continue;
                if (featureLayer.Name != capa)
                {
                    featureLayer.Selectable = false;
                }
                else
                {
                    featureLayer.Selectable = true;
                    featureClass = featureLayer.FeatureClass;
                }
            }
            
            if (m_lineFeedback != null)
            {
                //Use it to calculate new extent
                env = m_lineFeedback.Stop();
                //Select all feature that intersect with that shape
                //doc.FocusMap.
                doc.FocusMap.SelectByShape(env, null, false);
            }
            else
            {
                //Select by point
                doc.FocusMap.SelectByShape(_point, null, false);
            }

            m_lineFeedback = null;

            if (doc.FocusMap.SelectionCount > 0)
            {
                enumFeature = doc.FocusMap.FeatureSelection as IEnumFeature;
                enumFeature.Reset();
                feature = enumFeature.Next();
                ObjectId = feature.get_Value(feature.Fields.FindField("OBJECTID")).ToString();
                FeatClass = featureClass;
                IFeatureClassSelectExample(FeatClass, "OBJECTID = " + ObjectId.ToString(CultureInfo.CurrentCulture));
                formulario = new WPF.WPFLotes();
                formulario.Show();
                //TODO Lansa el formulario
                //Form frm = (Form)ObjFrm;
                //frm.Show();

                this.Enabled = true;

            }
            else
            {
                MessageBox.Show("Es Posible que la Capa que Desea Seleccionar no este Activa o no se encuientren registros en el area que se realizo la Operacion", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
          
        }
        public void IFeatureClassSelectExample(IFeatureClass featureClass, string Query)
        {
            
            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.WhereClause = Query;

            ISelectionSet selectionSet = featureClass.Select(queryFilter, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, null);
            ArcMap.Document.ActiveView.Refresh();
            ArcMap.Document.ActiveView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeoSelection, null, null);
           
        }
    }

}
